<template>
  <view class="my-course-page">
    <!-- 筛选栏 -->
    <scroll-view class="filter-bar" scroll-x>
      <text
        v-for="(item, i) in filterList"
        :key="i"
        class="filter"
        :class="{ active: currentTab === i }"
        @click="changeTab(i,item.value)"
      >{{ item.name }}</text>
    </scroll-view>
    <!-- 内容区 -->
    <view
      class="content-container"
      @touchstart="onTouchStart"
      @touchmove="onTouchMove"
      @touchend="onTouchEnd"
    >
      <view
        class="tab-content"
        :style="{ transform: `translateX(${(dragOffset - currentTab * 100)}%)`, transition: dragTransition }"
      >
        <view class="tab-pane" v-for="(item, tabIdx) in filterList" :key="tabIdx">
          <view class="course-list" v-if="currentTab === tabIdx">
            <view
              class="course-card"
              v-for="(course, idx) in courses[currentTab]"
              :key="idx"
            >
              <view class="course-main" @click="jumpDetails(course.productId)">
                <img class="cover" :src="course.productPic" />
                <view class="info">
                  <view class="title-row">
                    <text class="course-title">{{ course.productName }}</text>
                    <text class="progress-num">{{ Math.round(course.usedSessions/course.totalSessions*100) }}%</text>
                  </view>
                  <view class="progress-bar">
                    <view class="progress-inner" :style="{ width: course.usedSessions/course.totalSessions*100 + '%' }"></view>
                  </view>
                  <view class="progress-text">已完成 {{ course.usedSessions }}/{{ course.totalSessions }} 课时</view>
                </view>
              </view>
              <!-- 章节列表 -->
              <view
                class="chapter-section"
                v-if="course.courseOutline && course.courseOutline.length"
              >
                <view class="chapter-header" @click.stop="toggleOpen(tabIdx, idx,course.productId,course.type)">
                  <text class="chapter-section-title">课程章节</text>
                  <img class="chapter-arrow-img" :class="{ open: course.open }" src="https://fengqinghui.oss-cn-hangzhou.aliyuncs.com/monkey/monkey/zhanKaiMe.png" />
                </view>
                <view class="chapter-slide-wrapper">
                  <view
                    class="chapter-slide-content"
                    :class="{ 'slide-down': course.open }"
                  >
                    <TreeView
                      ref="treeView"
                      :rootData="course.courseOutline"
                      @toggle="onNodeToggled"
                      :isBuy="true"
                    />
                  </view>
                </view>
              </view>
            </view>
            <view v-if="courses[currentTab].length === 0" style="width: 100%;text-align: center;color: #6B7280;margin-top: 100px">
              暂时还没有记录哦
            </view>
          </view>
        </view>
      </view>
    </view>
    <u-popup :show="show" @close="close" :round="20">
      <view class="verify-popup fade-in">
        <view class="verify-title">请出示此核销码给商户</view>
        <view class="verify-desc">商户扫码后即可完成核销</view>
        <view class="verify-qrcode-box">
          <image :src="popupQrCode" class="verify-qrcode-img" mode="aspectFit" />
        </view>
        <view class="verify-divider"></view>
        <view v-if="popupCode" class="verify-code-ticket">
          <text class="verify-code-text">{{ popupCode }}</text>
        </view>
        <view class="verify-tip">请勿泄露此码，仅限本次核销使用</view>
      </view>
    </u-popup>
  </view>
</template>

<script>
import UCollapse from "../../../uni_modules/uview-ui/components/u-collapse/u-collapse.vue";
import TreeView from "../../../components/courseDetails/treeView.vue";
import {getAccessList, getAccessQrcode} from "../../../api/new";

export default {
  name: "index",
  components: {TreeView, UCollapse},
  data() {
    return {
      productId:0,
      type:100,
      show: false,
      popupQrCode: '',
      popupCode: '',
      filterList: [
        {
          name:'全部',
          value:'',
        },
        {
          name:'进行中',
          value:'ACTIVE',
        },
        {
          name:'已过期',
          value:'EXPIRED',
        },
      ],
      currentTab: 0,
      startX: 0,
      dragOffset: 0,
      dragTransition: 'transform 0.3s ease',
      threshold: 15, // 滑动阈值（像素百分比）
      courses: [
          [],[],[]
      ],
      propagation:[
        {
          limit:10,
          page:1,
        },
        {
          limit:10,
          page:1,
        },
        {
          limit:10,
          page:1,
        },
      ],
      showChapters: false,
      swipeDebounce: false, // 新增防抖变量
    }
  },
  onLoad(){
    this.getList()
  },
  onReachBottom(){
    this.getList()
  },
  methods: {
    jumpDetails(id) {
      uni.navigateTo({
        url: '/pages/discover/courseDetails/index?id=' + id
      })
    },
    getList(status){
      console.log(111)
      uni.showLoading({
        title: '加载中...'
      });
      let i = 0
      if (status === 'ACTIVE') {
        i = 1;
      } else if(status === 'EXPIRED') {
        i = 2;
      } else {
        i = 0;
      }
      let propagation={
        limit: this.propagation[i].limit,
        page: this.propagation[i].page,
      };
      if(status && status !== ''){
        propagation['status'] = status;
      }
      getAccessList(propagation).then( res => {
        if(res.data.list !== null && res.data.total>this.courses[i].length) {
          this.courses[i] = [...this.courses[i], ...res.data.list];
          // 为每个课程添加 open 字段，默认收起
          this.courses[i].forEach(course => {
            this.$set(course, 'open', false);
          });
          this.propagation[i].page = res.data.page+1
        }
        uni.hideLoading();
        console.log(res)
        console.log(this.courses)
      })
    },
    // 节点展开/折叠回调
    onNodeToggled(node) {
      console.log('节点状态变更:', node);
      if(this.type === 5){
        this.jumpDetails(this.productId)
        return
      }
      if (!node.isFinished){
        getAccessQrcode({id: node.ids, courseOutlineId: node.id}).then(res=>{
          this.popupQrCode = res.data.code;
          this.popupCode = res.data.desc;
          this.show = true;
        })
      } else {
        uni.showToast({title:'已核销'});
      }
    },
    changeTab(i,value) {
      this.currentTab = i;
      this.dragTransition = 'transform 0.3s ease';
      this.dragOffset = 0;
      this.getList(value);
    },
    getCoursesByTab(tabIdx) {
      const filter = this.filterList[tabIdx];
      if (filter === '全部') return this.courses;
      return this.courses.filter(c => c.status === filter);
    },
    toggleOpen(tabIdx, idx,productId,type) {
      this.productId = productId;
      this.type = type;
      console.log(this.courses[this.currentTab][idx].courseOutline)
      this.$refs.treeView[idx].id = this.courses[this.currentTab][idx].id
      this.$refs.treeView[idx].treeData = this.$refs.treeView[idx].addTreePropertiesReactive(this.courses[this.currentTab][idx].courseOutline, this)
      console.log(this.courses[this.currentTab][idx].open)
      // 保存处理后的值
      const processedValue = this.courses[this.currentTab][idx].open;

      // 清空输入框（关键步骤）
      this.courses[this.currentTab][idx].open = undefined;

      // 异步更新值（确保输入法已释放焦点）
      this.$nextTick(() => {
        this.courses[this.currentTab][idx].open = !processedValue;
        console.log(this.courses[this.currentTab][idx].open)
        this.$forceUpdate()

      });
    },
    onTouchStart(e) {
      this.startX = e.touches[0].clientX;
      this.lastTouchX = e.touches[0].clientX;
      this.touchStartTime = Date.now();
      this.dragOffset = 0;
      this.dragTransition = 'none';
      this.touchMoves = [];
    },
    onTouchMove(e) {
      const moveX = e.touches[0].clientX - this.startX;
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      // 记录触摸移动轨迹（用于防抖）
      this.touchMoves.push(moveX);
      if (this.touchMoves.length > 5) this.touchMoves.shift();
      // 防抖判断：如果最近5次移动距离变化不大，视为抖动，直接返回
      if (this.touchMoves.length >= 5 && Math.abs(this.touchMoves[4] - this.touchMoves[0]) < 10) {
        return;
      }
      // 增加最小移动阈值，避免轻微触碰触发
      const threshold = 60;
      if (Math.abs(moveX) < threshold) return;
      // 计算拖动百分比
      let dragPercentage = (moveX / windowWidth) * 100;
      // 禁止边界拖动
      if ((this.currentTab === 0 && dragPercentage > 0) || (this.currentTab === this.filterList.length - 1 && dragPercentage < 0)) {
        dragPercentage = 0;
      }
      this.dragOffset = dragPercentage;
    },
    onTouchEnd() {
      const windowWidth = uni.getSystemInfoSync().windowWidth;
      const moveX = this.dragOffset * windowWidth / 100;
      const touchDuration = Date.now() - this.touchStartTime;
      const touchDistance = Math.abs(moveX);
      // 计算滑动速度（像素/毫秒）
      const swipeSpeed = touchDistance / touchDuration;
      // 确保动画时间一致
      const animationDuration = 300;
      this.dragTransition = `transform ${animationDuration}ms cubic-bezier(0.0, 0.0, 1.0, 1.0)`;
      // 动态阈值计算（根据滑动速度调整，速度越快阈值越低）
      const baseThreshold = windowWidth / 5;
      const speedFactor = Math.min(1, swipeSpeed * 2);
      const dynamicThreshold = baseThreshold * (1 - speedFactor * 0.5);
      // 快速滑动判断
      const isQuickSwipe = (touchDuration < 300 && touchDistance > windowWidth * 0.1) || (swipeSpeed > 0.5);
      let targetTab = this.currentTab;
      if ((moveX > dynamicThreshold && this.currentTab > 0) || (isQuickSwipe && moveX > 0 && this.currentTab > 0)) {
        targetTab--;
      } else if ((moveX < -dynamicThreshold && this.currentTab < this.filterList.length - 1) || (isQuickSwipe && moveX < 0 && this.currentTab < this.filterList.length - 1)) {
        targetTab++;
      }
      targetTab = Math.max(0, Math.min(this.filterList.length - 1, targetTab));
      if (targetTab !== this.currentTab) {
        this.currentTab = targetTab;
        this.getList(this.filterList[this.currentTab].value);
      }
      setTimeout(() => {
        this.dragOffset = 0;
        this.dragTransition = 'none';
      }, animationDuration);
    },
    close() {
      this.show = false;
    }
  }
}
</script>

<style scoped lang="scss">
/deep/ .u-cell__title-text{
  font-weight: 600 !important;
}
.my-course-page {
  background: #fcfaf6;
  min-height: 100vh;
  padding-bottom: 70px;
  .filter-bar {
    display: block;
    white-space: nowrap;
    overflow-x: auto;
    padding: 20px 0 10px 20px;
    &::-webkit-scrollbar {
      display: none;
    }
    .filter {
      display: inline-block;
      padding: 6px 18px;
      border-radius: 20px;
      background: #f7f3ed;
      color: #a97a4c;
      font-size: 16px;
      margin-right: 12px;
      transition: background 0.2s, color 0.2s;
      &.active {
        background: #a97a4c;
        color: #fff;
      }
    }
  }
  .content-container {
    width: 100%;
    overflow: hidden;
    position: relative;
    .tab-content {
      display: flex;
      width: 100%;
      .tab-pane {
        flex-shrink: 0;
        width: 100%;
      }
    }
  }
  .course-list {
    padding: 0 16px;
    .course-card {
      background: #fff;
      border-radius: 16px;
      margin-bottom: 18px;
      box-shadow: 0 2px 8px #f3f1ed;
      .course-main {
        display: flex;
        align-items: center;
        padding: 16px;
        border-bottom: 2px solid #fbf9f5;
        .cover {
          width: 64px;
          height: 64px;
          border-radius: 8px;
          object-fit: cover;
          margin-right: 12px;
          flex-shrink: 0;
        }
        .info {
          flex: 1;
          min-width: 0;
          .title-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            .course-title {
              font-size: 18px;
              font-weight: 600;
              overflow: hidden;
              text-overflow: ellipsis;
              white-space: nowrap;
              flex: 1;
              min-width: 0;
            }
            .progress-num {
              color: #a97a4c;
              font-size: 15px;
              margin-left: 8px;
              flex-shrink: 0;
            }
          }
          .progress-bar {
            background: #f7f3ed;
            border-radius: 6px;
            height: 8px;
            margin: 8px 0;
            .progress-inner {
              background: #a97a4c;
              height: 100%;
              border-radius: 6px;
              transition: width 0.3s;
            }
          }
          .progress-text {
            color: #a97a4c;
            font-size: 14px;
          }
        }
      }
      .chapter-section {
        border-radius: 10px;
        .chapter-header {
          display: flex;
          align-items: center;
          justify-content: space-between;
          padding: 16px;
          cursor: pointer;
          width: 100%;
          height: 80rpx;
          .chapter-section-title {
            font-size: 16px;
            font-weight: 600;
            color: #222;
          }
          .chapter-arrow-img {
            width: 18px;
            height: 18px;
            margin-left: 6px;
            transition: transform 0.2s;
            display: inline-block;
            transform: rotate(180deg);
            &.open {
              transform: rotate(360deg);
            }
          }
        }
        .chapter-list {
          .chapter-row {
            display: flex;
            align-items: center;
            justify-content: space-between;
            background: #fff;
            border-radius: 8px;
            margin: 4px 0;
            padding: 10px 20px;
            box-shadow: 0 1px 2px #f3f1ed;
            .chapter-title-box {
              flex: 1;
              min-width: 0;
              margin-right: 8px;
              display: flex;
              flex-direction: column;
              .chapter-title {
                font-size: 15px;
                color: #222;
                font-weight: 500;
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                display: block;
              }
              .chapter-progress {
                font-size: 13px;
                color: #a7aab3;
                margin-top: 2px;
                display: block;
              }
            }
            .chapter-status {
              font-size: 13px;
              padding: 2px 14px;
              border-radius: 12px;
              flex-shrink: 0;
              &.finished {
                background: #e6e9ed;
                color: #a7aab3;
              }
              &.verify {
                background: #f7e7d7;
                color: #a97a4c;
                cursor: pointer;
              }
            }
          }
        }
      }
    }
  }
}

/* 章节展开收起动画 */
.chapter-fade-enter-active, .chapter-fade-leave-active {
  transition: all 0.3s cubic-bezier(.55,0,.1,1);
  overflow: hidden;
}
.chapter-fade-enter, .chapter-fade-leave-to {
  opacity: 0;
  max-height: 0;
}
.chapter-fade-enter-to, .chapter-fade-leave {
  opacity: 1;
  max-height: 1000px;
}

.chapter-slide-wrapper {
  overflow: hidden;
  margin: 0;
}

.chapter-slide-content {
  max-height: 0;
  padding-top: 0;
  padding-bottom: 0;
  opacity: 0;
  transition: all 0.5s cubic-bezier(.55,0,.1,1);
}

.chapter-slide-content.slide-down {
  max-height: 1000px;
  padding-top: 10px;
  padding-bottom: 10px;
  opacity: 1;
}

.verify-popup {
  background: linear-gradient(135deg, #fff8f1 0%, #f7f3ed 100%);
  box-shadow: 0 8px 32px rgba(169, 122, 76, 0.12);
  border-radius: 20px;
  animation: fadeIn 0.4s;
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx;
  .verify-title {
    font-size: 22px;
    font-weight: bold;
    color: #a97a4c;
    text-align: center;
    margin-bottom: 16px;
  }
  .verify-desc {
    font-size: 15px;
    color: #888;
    text-align: center;
    margin-bottom: 24px;
  }
  .verify-qrcode-box {
    background: #f5f7f9;
    border-radius: 12px;
    padding: 32rpx;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .verify-qrcode-img {
    width: 220rpx;
    height: 220rpx;
    background: #fff;
    border-radius: 8px;
    display: block;
  }
  .verify-divider {
    width: 60%;
    height: 1px;
    background: #f0e6d8;
    margin: 24px auto 12px auto;
    border-radius: 1px;
  }
  .verify-code-ticket {
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 0;
    margin-bottom: 8px;
    .verify-code-text {
      color: #a97a4c;
      font-size: 32px;
      font-family: 'DIN', Arial, sans-serif;
      letter-spacing: 4px;
      background: #fff7ed;
      padding: 12px 32px;
      border-radius: 16px;
      box-shadow: 0 2px 8px #f3f1ed;
      font-weight: bold;
    }
  }
  .verify-tip {
    color: #bfa074;
    font-size: 14px;
    text-align: center;
    margin-top: 8px;
    letter-spacing: 1px;
  }
}
.fade-in {
  animation: fadeIn 0.4s;
}
@keyframes fadeIn {
  from { opacity: 0; transform: translateY(30px);}
  to { opacity: 1; transform: translateY(0);}
}
</style>